package net.maku.generator.config.template;

import cn.hutool.core.util.StrUtil;
import net.maku.generator.common.exception.ServerException;
import net.maku.generator.domain.query.Query;
import net.maku.generator.common.utils.JsonUtils;
import net.maku.generator.domain.entity.TemplateEntity;
import net.maku.generator.service.TemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 代码生成配置内容
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
public class GeneratorConfig {
    private String template;

    @Autowired
    private TemplateService templateService;

    public GeneratorConfig(String template) {
        this.template = template;
    }

    public GeneratorInfo getGeneratorConfig(Long templateGroupId) {
        // 模板路径，如果不是以/结尾，则添加/
        if (!StrUtil.endWith(template, '/')) {
            template = template + "/";
        }

        // 模板配置文件
        InputStream isConfig = this.getClass().getResourceAsStream(template + "config.json");
        if (isConfig == null) {
            throw new ServerException("模板配置文件，config.json不存在");
        }

        try {
            // 读取模板配置文件
            String configContent = StreamUtils.copyToString(isConfig, StandardCharsets.UTF_8);
            GeneratorInfo generator = JsonUtils.parseObject(configContent, GeneratorInfo.class);
            assert generator != null;
            Query query = new Query();
            query.setTemplateGroupId(templateGroupId);
            List<TemplateEntity> list = templateService.list(query);
            List<TemplateInfo> list1 = list.stream().map(t -> {
                TemplateInfo templateInfo = new TemplateInfo();
                templateInfo.setId(t.getId());
                templateInfo.setTemplateName(t.getTemplateName());
                templateInfo.setTemplateContent(t.getTemplateContent());
                templateInfo.setGeneratorPath(t.getGeneratorPath());
                return templateInfo;
            }).toList();
            generator.setTemplates(list1);
            return generator;
        } catch (IOException e) {
            throw new ServerException("读取config.json配置文件失败");
        }
    }

    public TemplateInfo getTemplateInfo(Long templateId) {
        TemplateEntity template = templateService.getById(templateId);
        if (template == null) {
            throw new ServerException("模板不存在");
        }
        TemplateInfo templateInfo = new TemplateInfo();
        templateInfo.setId(template.getId());
        templateInfo.setTemplateName(template.getTemplateName());
        templateInfo.setTemplateContent(template.getTemplateContent());
        templateInfo.setGeneratorPath(template.getGeneratorPath());
        return templateInfo;
    }

}
